<template>
  <div class="my-page">
    <div class="page-content">
      <!-- 未登录状态 -->
      <div v-if="!userStore.isLoggedIn" class="user-section">
        <div class="user-avatar">
          <img src="@/assets/imgs/avatar_unlogin.png" alt="用户头像" />
        </div>
        <div class="user-info">
          <h3 class="user-name">未登录用户</h3>
          <p class="user-desc">点击下方按钮登录或注册</p>
        </div>
      </div>
      
      <!-- 已登录状态 -->
      <div v-else class="user-section logged-in">
        <div class="user-card">
          <div class="user-avatar-container">
            <AvatarUpload
              :avatar-url="userStore.userInfo.avatar"
              :size="80"
              :default-text="getUserInitials(userStore.userInfo.name)"
              @upload-success="handleAvatarUploadSuccess"
              @upload-error="handleAvatarUploadError"
            />
            <div class="avatar-badge">
              <span class="badge-icon">✓</span>
            </div>
          </div>
          <div class="user-info">
            <h3 class="user-name">{{ userStore.userInfo.name || '用户' }}</h3>
            <div class="user-status">
              <span class="status-dot"></span>
              <span class="status-text">在线</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 未登录时的登录按钮 -->
      <div v-if="!userStore.isLoggedIn" class="action-buttons">
        <button class="login-btn" @click="goToAuth">
          <span class="btn-text">登录 / 注册</span>
          <span class="btn-icon">→</span>
        </button>
      </div>
      
      <!-- 已登录时的用户信息管理 -->
      <div v-else class="user-management">
        <div class="management-section">
          <div class="section-header">
            <div class="section-icon">👤</div>
            <h4 class="section-title">个人信息</h4>
          </div>
          <div class="info-list">
            <div class="info-item" @click="showNameDialog = true">
              <div class="info-icon">✏️</div>
              <div class="info-content">
                <span class="info-label">用户名</span>
                <span class="info-value">{{ userStore.userInfo.name || '未设置' }}</span>
              </div>
              <div class="info-arrow">›</div>
            </div>
            <div class="info-item">
              <div class="info-icon">📱</div>
              <div class="info-content">
                <span class="info-label">手机号</span>
                <span class="info-value">{{ userStore.userInfo.phone || '未设置' }}</span>
              </div>
            </div>
            <div class="info-item" @click="showPasswordDialog = true">
              <div class="info-icon">🔒</div>
              <div class="info-content">
                <span class="info-label">密码</span>
                <span class="info-value">修改密码</span>
              </div>
              <div class="info-arrow">›</div>
            </div>
          </div>
        </div>
        
        <div class="action-section">
          <div class="action-buttons">
            <button class="logout-btn" @click="handleLogout">
              <div class="btn-icon">🚪</div>
              <span class="btn-text">退出登录</span>
              <div class="btn-arrow">›</div>
            </button>
          </div>
        </div>
      </div>
      
      <div class="features-section">
        <div class="section-header">
          <div class="section-icon">⚡</div>
          <h4 class="section-title">功能预览</h4>
        </div>
        <div class="feature-grid">
          <div class="feature-item">
            <div class="feature-icon">🏠</div>
            <div class="feature-text">
              <h5>房源管理</h5>
              <p>管理您的房源信息</p>
            </div>
            <div class="feature-arrow">›</div>
          </div>
          <div class="feature-item" @click="goToBooking">
            <div class="feature-icon">📋</div>
            <div class="feature-text">
              <h5>订单管理</h5>
              <p>查看预约记录</p>
            </div>
            <div class="feature-arrow">›</div>
          </div>
          <div class="feature-item">
            <div class="feature-icon">⚙️</div>
            <div class="feature-text">
              <h5>设置</h5>
              <p>个人设置与偏好</p>
            </div>
            <div class="feature-arrow">›</div>
          </div>
          <div class="feature-item" @click="goToFavorite">
            <div class="feature-icon">💬</div>
            <div class="feature-text">
              <h5>收藏</h5>
              <p>收藏的房源</p>
            </div>
            <div class="feature-arrow">›</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 修改用户名弹窗 -->
    <div v-if="showNameDialog" class="dialog-overlay" @click="showNameDialog = false">
      <div class="dialog-content" @click.stop>
        <h3 class="dialog-title">修改用户名</h3>
        <div class="form-group">
          <label class="form-label">新用户名</label>
          <input 
            v-model="nameForm.newName"
            type="text" 
            class="form-input"
            placeholder="请输入新用户名"
            :class="{ error: nameErrors.newName }"
            @blur="validateName(nameForm.newName)"
          />
          <div v-if="nameErrors.newName" class="error-message">
            {{ nameErrors.newName }}
          </div>
        </div>
        <div class="dialog-actions">
          <button class="btn-cancel" @click="showNameDialog = false">取消</button>
          <button class="btn-confirm" @click="handleChangeName" :disabled="isChangingName">
            {{ isChangingName ? '修改中...' : '确认' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 修改密码弹窗 -->
    <div v-if="showPasswordDialog" class="dialog-overlay" @click="showPasswordDialog = false">
      <div class="dialog-content" @click.stop>
        <h3 class="dialog-title">修改密码</h3>
        <div class="form-group">
          <label class="form-label">原密码</label>
          <input 
            v-model="passwordForm.oldPassword"
            type="password" 
            class="form-input"
            placeholder="请输入原密码"
          />
        </div>
        <div class="form-group">
          <label class="form-label">新密码</label>
          <input 
            v-model="passwordForm.newPassword"
            type="password" 
            class="form-input"
            placeholder="请输入新密码"
          />
        </div>
        <div class="form-group">
          <label class="form-label">确认新密码</label>
          <input 
            v-model="passwordForm.confirmPassword"
            type="password" 
            class="form-input"
            placeholder="请再次输入新密码"
          />
        </div>
        <div class="dialog-actions">
          <button class="btn-cancel" @click="showPasswordDialog = false">取消</button>
          <button class="btn-confirm" @click="handleChangePassword" :disabled="isChangingPassword">
            {{ isChangingPassword ? '修改中...' : '确认' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import AvatarUpload from '@/components/AvatarUpload.vue'

const router = useRouter()
const userStore = useUserStore()

// 弹窗状态
const showNameDialog = ref(false)
const showPasswordDialog = ref(false)

// 用户名表单
const nameForm = reactive({
  newName: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单错误信息
const nameErrors = reactive({
  newName: ''
})

// 加载状态
const isChangingName = ref(false)
const isChangingPassword = ref(false)

// 页面加载时刷新用户信息
onMounted(async () => {
  // 检查是否有token但没有用户信息，需要刷新
  if (userStore.isLoggedIn && (!userStore.userInfo || !userStore.userInfo.name)) {
    try {
      await userStore.refreshUserInfo()
    } catch (error) {
      console.warn('刷新用户信息失败:', error)
    }
  }
})

const goToAuth = () => {
  router.push('/auth')
}

const goToBooking = () => {
  router.push('/booking')
}

const goToFavorite = () => {
  router.push('/favorite')
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await userStore.userLogout()
    ElMessage.success('已退出登录')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出登录失败')
    }
  }
}

// 验证用户名
const validateName = (value) => {
  if (!value.trim()) {
    nameErrors.newName = '用户名不能为空'
    return false
  }
  
  if (value.length < 2) {
    nameErrors.newName = '用户名长度不能少于2位'
    return false
  }
  
  if (value.length > 20) {
    nameErrors.newName = '用户名长度不能超过20位'
    return false
  }
  
  nameErrors.newName = ''
  return true
}

// 处理修改用户名
const handleChangeName = async () => {
  if (!validateName(nameForm.newName)) {
    return
  }
  
  isChangingName.value = true
  
  try {
    await userStore.changeUserName(nameForm.newName)
    ElMessage.success('用户名修改成功')
    showNameDialog.value = false
    nameForm.newName = ''
  } catch (error) {
    ElMessage.error(error.message || '用户名修改失败')
  } finally {
    isChangingName.value = false
  }
}

// 处理修改密码
const handleChangePassword = async () => {
  if (!passwordForm.oldPassword.trim()) {
    ElMessage.warning('请输入原密码')
    return
  }
  
  if (!passwordForm.newPassword.trim()) {
    ElMessage.warning('请输入新密码')
    return
  }
  
  if (passwordForm.newPassword.length < 6) {
    ElMessage.warning('新密码长度不能少于6位')
    return
  }
  
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.warning('两次输入的新密码不一致')
    return
  }
  
  isChangingPassword.value = true
  
  try {
    await userStore.changeUserPassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    ElMessage.success('密码修改成功，请重新登录')
    
    // 关闭弹窗
    showPasswordDialog.value = false
    
    // 清空表单
    Object.keys(passwordForm).forEach(key => {
      passwordForm[key] = ''
    })
    
    // 延迟1秒后自动退出登录并跳转到登录页面
    setTimeout(async () => {
      try {
        await userStore.userLogout()
        ElMessage.info('已自动退出登录，请使用新密码重新登录')
        router.push('/auth')
      } catch (error) {
        console.warn('自动退出登录失败:', error)
        // 即使退出失败也要跳转到登录页面
        ElMessage.info('请使用新密码重新登录')
        router.push('/auth')
      }
    }, 1000)
    
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败')
  } finally {
    isChangingPassword.value = false
  }
}

// 获取用户姓名首字母
const getUserInitials = (name) => {
  if (!name) return '用'
  return name.charAt(0).toUpperCase()
}

// 处理头像上传成功
const handleAvatarUploadSuccess = (avatarUrl) => {
  console.log('头像上传成功:', avatarUrl)
  // 用户信息已经在store中自动更新，这里可以添加额外的成功处理逻辑
}

// 处理头像上传失败
const handleAvatarUploadError = (error) => {
  console.error('头像上传失败:', error)
  // 错误提示已经在组件内部处理，这里可以添加额外的错误处理逻辑
}

</script>

<style scoped>
.my-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f8ff 0%, #f5f5f5 30%, #f5f5f5 100%);
  padding: 20px;
}

.page-content {
  background-color: #fff;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  max-width: 400px;
  margin: 0 auto;
}

.user-section {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.user-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.action-buttons {
  margin-bottom: 30px;
}

.login-btn {
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px 20px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.btn-text {
  flex: 1;
  text-align: left;
}

.btn-icon {
  font-size: 18px;
  transition: transform 0.3s ease;
}

.login-btn:hover .btn-icon {
  transform: translateX(4px);
}

.features-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.feature-item {
  background: #fafbfc;
  border-radius: 12px;
  padding: 20px 16px;
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100px;
}

.feature-item:hover {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-color: #e1e5ff;
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
}

.feature-item:hover .feature-arrow {
  transform: translateX(4px);
  color: #667eea;
}

.feature-icon {
  font-size: 28px;
  margin-bottom: 12px;
  transition: transform 0.3s ease;
}

.feature-item:hover .feature-icon {
  transform: scale(1.1);
}

.feature-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.feature-text h5 {
  font-size: 15px;
  font-weight: 600;
  margin: 0 0 6px 0;
  color: #333;
}

.feature-text p {
  font-size: 12px;
  margin: 0;
  color: #666;
  line-height: 1.4;
}

.feature-arrow {
  position: absolute;
  top: 12px;
  right: 12px;
  font-size: 16px;
  color: #ccc;
  transition: all 0.3s ease;
}

/* 添加浮动动画 */
@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(5deg); }
}

/* 添加淡入动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-section,
.management-section,
.features-section {
  animation: fadeInUp 0.6s ease-out;
}

.user-card {
  animation: fadeInUp 0.8s ease-out;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-page {
    padding: 16px;
  }
  
  .page-content {
    padding: 20px;
    max-width: 100%;
  }
  
  .user-card {
    padding: 20px;
  }
  
  .user-avatar {
    width: 70px;
    height: 70px;
  }
  
  .user-name {
    font-size: 20px;
  }
  
  .user-desc {
    font-size: 14px;
  }
  
  .login-btn {
    padding: 12px 18px;
    font-size: 15px;
  }
  
  .management-section,
  .features-section {
    padding: 20px;
  }
  
  .info-item {
    padding: 14px;
  }
  
  .feature-item {
    padding: 16px 12px;
    min-height: 90px;
  }
  
  .feature-icon {
    font-size: 24px;
  }
  
  .feature-text h5 {
    font-size: 14px;
  }
  
  .feature-text p {
    font-size: 11px;
  }
  
  .dialog-content {
    padding: 20px;
    margin: 20px;
  }
}

@media (max-width: 480px) {
  .page-content {
    padding: 16px;
  }
  
  .user-card {
    padding: 16px;
  }
  
  .user-avatar {
    width: 60px;
    height: 60px;
  }
  
  .user-name {
    font-size: 18px;
  }
  
  .feature-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .feature-item {
    min-height: 80px;
  }
}

/* 用户管理样式 */
.user-management {
  margin-bottom: 30px;
}

/* 已登录用户卡片样式 */
.user-section.logged-in {
  margin-bottom: 25px;
}

.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 24px;
  color: white;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.user-card::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -20%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

.user-avatar-container {
  position: relative;
  margin-bottom: 16px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid rgba(255, 255, 255, 0.3);
  position: relative;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-badge {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 24px;
  height: 24px;
  background: #4CAF50;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid white;
}

.badge-icon {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.user-info {
  text-align: center;
}

.user-name {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-desc {
  font-size: 16px;
  margin: 0 0 12px 0;
  opacity: 0.9;
}

.user-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin-top: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #4CAF50;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-text {
  font-size: 14px;
  opacity: 0.9;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.management-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f8f9fa;
}

.section-icon {
  font-size: 20px;
  margin-right: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafbfc;
  border: 1px solid #f0f0f0;
}

.info-item:hover {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-color: #e1e5ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.1);
}

.info-icon {
  font-size: 18px;
  margin-right: 16px;
  width: 24px;
  text-align: center;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.info-arrow {
  font-size: 20px;
  color: #999;
  font-weight: bold;
  transition: transform 0.3s ease;
}

.info-item:hover .info-arrow {
  transform: translateX(4px);
  color: #667eea;
}

.action-section {
  margin-top: 20px;
}

.logout-btn {
  width: 100%;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
  border: none;
  padding: 16px 24px;
  border-radius: 16px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4px 16px rgba(255, 107, 107, 0.3);
}

.logout-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 24px rgba(255, 107, 107, 0.4);
}

.btn-icon {
  font-size: 18px;
}

.btn-text {
  flex: 1;
  text-align: center;
}

.btn-arrow {
  font-size: 18px;
  font-weight: bold;
  transition: transform 0.3s ease;
}

.logout-btn:hover .btn-arrow {
  transform: translateX(4px);
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 16px;
  padding: 24px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  text-align: center;
}

.dialog-content .form-group {
  margin-bottom: 16px;
}

.dialog-content .form-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.dialog-content .form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: #fafbfc;
  box-sizing: border-box;
}

.dialog-content .form-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.dialog-content .form-input.error {
  border-color: #ff4757;
  background: #fff5f5;
}

.error-message {
  color: #ff4757;
  font-size: 12px;
  margin-top: 4px;
}

.dialog-actions {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.btn-cancel {
  flex: 1;
  padding: 12px 20px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  background: white;
  color: #666;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel:hover {
  border-color: #ccc;
  background: #f8f9fa;
}

.btn-confirm {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-confirm:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.btn-confirm:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dialog-content {
    padding: 20px;
    margin: 20px;
  }
  
  .info-item {
    padding: 10px 0;
  }
  
  .info-label {
    min-width: 50px;
    font-size: 13px;
  }
  
  .info-value {
    font-size: 13px;
  }
}
</style>
